import sys
from PyQt5.QtWidgets import (
    QApplication,
    QLineEdit,
    QWidget,
    QHBoxLayout,
    QPushButton,
    QLabel,
    QSpinBox,
    QVBoxLayout,
)
from PyQt5.QtCore import QObject, pyqtSignal
from .clientAPI import ClientAPI


class ConnectResult(QObject):
    resultSignal = pyqtSignal(bool)


class ConnectView(QWidget):
    def __init__(self, api: ClientAPI, parent=None):
        super().__init__(parent)
        self.api = api
        self.signal = ConnectResult()
        self.InitUI()

    def InitUI(self):
        self.setWindowTitle("Connect to Server")

        hbox = QHBoxLayout()
        hbox.addWidget(QLabel("Server:"))
        self.serverLineEdit = QLineEdit("localhost")
        hbox.addWidget(self.serverLineEdit)
        hbox.addWidget(QLabel("Port:"))
        self.portSpinBox = QSpinBox()
        self.portSpinBox.setMinimum(1)
        self.portSpinBox.setMaximum(65535)
        self.portSpinBox.setValue(5000)
        hbox.addWidget(self.portSpinBox)
        self.connectButton = QPushButton("Connect")
        self.connectButton.clicked.connect(self.OnConnect)
        hbox.addWidget(self.connectButton)

        vbox = QVBoxLayout()
        self.ServerInfoLabel = QLabel("none")
        vbox.addLayout(hbox)
        vbox.addWidget(self.ServerInfoLabel)

        self.setLayout(vbox)
        self.show()

    def OnConnect(self):
        server = self.serverLineEdit.text()
        port = self.portSpinBox.value()
        if self.api.TestConnection(f"http://{server}:{port}"):
            self.signal.resultSignal.emit(True)
            info = self.api.GetServerInfo()
            if info:
                self.ServerInfoLabel.setText(f"Server Info: {info}")
        else:
            self.signal.resultSignal.emit(False)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ConnectView()
    sys.exit(app.exec_())
